<template>
  <div>
    <div>
      <!-- 答案信息表单 -->
      <FormPanel
        ref="formPanel"
        :list="formList"
        formType="add"
        labelWidth="100"
        :isSubmitBtn="false"
        @formChange="formChangeHandle"
      />

      <!-- 选项信息表格 -->
      <FilterTable ref="table"
        :columns="answerColumns"
        :dataSource="answerGroupList"
        :isSelectColumn="false"
        :isToperInfo="false"
        columnsRef="ysjAnswerPanelTable"
        :onColumnsChange="columns => (this.answerColumns = columns)">

        <template slot="controls">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addAnswer()">新增选项</el-button>
        </template>
      </FilterTable>
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button @click="closeDrawer(false)">取 消</el-button>
      <el-button @click="commit" type="primary" :loading="loginBtnState">{{ btnText }}</el-button>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex';
import * as types from '@/api/customerCare/visitRules/questionnaireMake/types';
import moment from 'moment';
import { getAnswerEditInfo, saveAnswerInfo, editAnswerInfo, queryAnswersPagByIds} from '@/api/customerCare/visitRules/questionnaireMake';
import { dictionary } from '@/utils/dictMixin';

export default {
  name: 'AnswerPanel',
  mixins: [dictionary],
  props: {
    answerGroupId: String,
    type: String,
    recordVersion: String
  },
  data() {
    this.conf = { add: '保 存', edit: '修 改' };
    this.BaseTable = null;
    return {
      formList: this.createFormList(), //答案表单
      answerGroupList: [], //选项数据表格
      answerColumns: this.createAnswerColumns(), //选项表格列
      answer: {}
    };
  },
  computed: {
    ...mapState('app', ['btnLoading']),
    loginBtnState() {
      return this.btnLoading[types.SAVE];
    },
    btnText() {
      return this.conf[this.type];
    }
  },
  created() {
    this.getAnswer();
  },
  methods: {
    //获取答案信息
    async getAnswer() {
      if (this.answerGroupId) {
        let searchDetail = {
          answerGroupId: this.answerGroupId
        };
        const res = await getAnswerEditInfo(searchDetail);
        if (res.resultCode == 200) {
          this.formList.forEach(x => x.initialValue = res.data[x.fieldName]);
        } else {
          this.$message.error('获取答案信息失败');
          return;
        }
        searchDetail.limit = 9999;
        searchDetail.pageNum = 1;
        const resList = await queryAnswersPagByIds(searchDetail);
        if(resList.resultCode == 200){
          this.answerGroupList = resList.data.records;
        }else{
          this.$message.error('获取答案选项失败');
          return;
        }
      } else {
        this.answer = {
          answerGroupName: '',
          answerGroupDescript: '',
          isValid: 10041001,
          dataSources: 10451001
        };
        this.answerGroupList = [];
      }
    },
    //创建表单列
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '答案名称',
          fieldName: 'answerGroupName',
          disabled: this.type == 'edit',
          rules: [{ required: true, message: '请填写答案名称', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '答案说明',
          fieldName: 'answerGroupDescript',
          rules: [{ required: true, message: '请填写答案说明', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '是否启用',
          fieldName: 'isValid',
          itemList: this.createDictList('1004'),
          rules: [{ required: true, message: '请选择是否启用', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '数据来源',
          fieldName: 'dataSources',
          itemList: this.createDictList('1045'),
          initialValue: 10451001,
          disabled: true
        }
      ];
    },
    //关闭
    closeDrawer(refresh) {
      if (refresh) {
        this.$emit('changeHandle', { dataSources: 10451001 });
      }
      this.$emit('close', false);
    },
    //选项表格列
    createAnswerColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 50,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.delAnswer(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '选项内容',
          dataIndex: 'answer',
          filterType: 'input',
          showOverflowTooltip: true,
          editable: true,
          editType: 'input',
          editRequired: true,
          rules: [{ required: true, message: '请填写选项内容', trigger: 'blur' }]
        },
        {
          title: '排列顺序',
          dataIndex: 'answerSort',
          filterType: 'input',
          editable: true,
          editType: 'input',
          editRequired: true,
          editPattern: /^[0-9]+$/,
          rules: [{ required: true, message: '请填写排列顺序', trigger: 'blur' }]
        }
      ];
    },
    //新增选项
    addAnswer() {
      let answer = {
        answer: '',
        answerSort: this.answerGroupList.length+1
      };
      this.answerGroupList.push(answer);
    },
    //删除选项
    delAnswer(row) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.answerGroupList.splice(row.$index, 1);
      });
    },
    //点击提交
    commit() {
      //调用表单验证
      this.$refs.formPanel.SUBMIT_FORM();
    },
    //表单验证回调，传回表单参数
    formChangeHandle(val) {
      //检验是否添加选项信息
      if (this.answerGroupList.length === 0) {
        this.$message.info('请添加选项信息');
        return;
      }
      let a = true;
      //检验选项信息是否正确
      for (let i = 0; i < this.answerGroupList.length; i++) {
        if (this.answerGroupList[i].answer == '' || this.answerGroupList[i].answer == null || this.answerGroupList[i].answer == undefined) {
          this.$message({
            type: 'error',
            message: '选项内容不能为空!'
          });
          a = false;
          break;
        }
        if (this.answerGroupList[i].answerSort == '' || this.answerGroupList[i].answerSort == null || this.answerGroupList[i].answerSort == undefined) {
          this.$message({
            type: 'error',
            message: '排列顺序不能为空!'
          });
          a = false;
          break;
        }
      }
      if (a) {
        //提交保存
        this.answer.answerGroupName = val.answerGroupName;
        this.answer.answerGroupDescript = val.answerGroupDescript;
        this.answer.dataSources = val.dataSources;
        this.answer.isValid = val.isValid;
        this.answer.answerGroupList = this.answerGroupList;
        if(this.type == 'add'){
          saveAnswerInfo(this.answer).then(res => {
            if (res.resultCode === 200) {
              this.$message.success('保存成功');
              this.closeDrawer(true);
            } else {
              this.$message.error('保存失败');
            }
          });
        }else{
          this.answer.answerGroupId = this.answerGroupId;
          this.answer.recordVersion = this.recordVersion;
          editAnswerInfo(this.answer).then(res => {
            if (res.resultCode === 200) {
              this.$message.success('修改成功');
              this.closeDrawer(true);
            } else {
              this.$message.error('修改失败');
            }
          })
        }
      }
    }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  }
};
</script>
